package com.chenbei.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenbei.system.domain.SysMenu;
import com.chenbei.system.domain.SysRoleMenu;
import com.chenbei.system.mapper.SysRoleMenuMapper;
import com.chenbei.system.service.ISysMenuService;
import com.chenbei.system.service.ISysRoleMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysRoleMenuService extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    @Transactional
    @Override
    public void saveOrUpdate(Long roleId, List<Long> menuIds) {
        if (roleId != null && roleId > 0) {
            LambdaQueryWrapper<SysRoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysRoleMenu::getRoleId, roleId);
            remove(lambdaQueryWrapper);

            if (menuIds != null && !menuIds.isEmpty()) {
                List<SysRoleMenu> sysRoleMenus = menuIds.stream().map(menuId -> {
                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setRoleId(roleId);
                    sysRoleMenu.setMenuId(menuId);
                    sysRoleMenu.setCreateTime(LocalDateTime.now());

                    return sysRoleMenu;
                }).collect(Collectors.toList());
                saveBatch(sysRoleMenus);
            }
        }
    }

    @Override
    public List<SysMenu> listByRoleId(List<Long> roleIds) {
        return baseMapper.listByRoleIds(roleIds);
    }
}
